﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using BCS.Business;
using BCS.Common;
using BCS.RenderBusiness;

namespace BCS.WinFormAppGui
{
        public partial class MainForm : Form
        {
                private BusinessCache cache = BusinessCache.Instance;

                private Thread backgroundWorkThread;

                private Image LockBitmap = Bitmap.FromFile(@"Res\Images\Lock.png");
                private Image UnLockBitmap = Bitmap.FromFile(@"Res\Images\UnLock.png");

                public MainForm()
                {
                        InitializeComponent();
                }

                private void Form_Load(object sender, EventArgs e)
                {
                        UpdateUI();

                        MainTimer.Start();

                        cache.IsAutoCount = false;
                        cache.Permission = Permissions.查询权限;

                        CameraRenderer.InitializeEnvironment();

                        if (!cache.Load())
                        {
                                MessageBox.Show("数据库加载失败");
                                Close();
                        }

                        cache.IsAutoCount = false;

                        CameraCountLabel.Text = cache.Camera.Count.ToString();
                        TotalCountLabel.Text = cache.TotalCount.ToString();
                        TeamNameLabel.Text = cache.CurrentTeam.Name;
                        TeamCountLabel.Text = cache.CurrentTeamCount.ToString();
                        TeamStartTimeLabel.Text = cache.CurrentTeamStartTime;

                        cache.MainPictureBoxGraphics = MainPictureBox.CreateGraphics();
                        cache.SourcePictureBoxGraphics = SourcePictureBox.CreateGraphics();
                        cache.BackPictureBoxGraphics = BackPictureBox.CreateGraphics();
                        cache.SubPictureBoxGraphics = SubPictureBox.CreateGraphics();

                        //调试信息
                        string debugFile = Path.Combine(Application.StartupPath, "调试.txt");
                        if (File.Exists(debugFile))
                        {
                                cache.DebugWriter = new StreamWriter(debugFile, false);
                        }

                        backgroundWorkThread = new Thread(BackgroundWorkThreadFunction);
                        backgroundWorkThread.Start();
                }

                private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
                {
                        backgroundWorkThread.Abort();

                        cache.GraphicsCard.StopSnapShotAsync();
                        cache.GraphicsCard.StopGraphicsCard();

                        if (cache.DebugWriter != null)
                        {
                                cache.DebugWriter.Flush();
                                cache.DebugWriter.Close();
                        }
                }

                public static unsafe void BackgroundWorkThreadFunction()
                {
                        BusinessCache bc = BusinessCache.Instance;
                        bc.CountTicks = 0;

                        for (; ; )
                        {
                                bc.GraphicsCard.UpdateSnapingFrameNumber();

                                if (bc.GraphicsCard.CompleteFrameIndex > -1)
                                {
                                        bc.GraphicsCard.TransformSnapImageData(bc.Camera);

                                        bc.Camera.Analyse();

                                        CameraRenderer.Render(bc.MainPictureBoxGraphics.GetHdc().ToPointer(), bc.Camera);
                                        bc.MainPictureBoxGraphics.ReleaseHdc();

                                        CameraRenderer.Render(bc.SourcePictureBoxGraphics.GetHdc().ToPointer(), bc.Camera.SourceBuffer, Global.AeraWidth, Global.AeraHeight);
                                        bc.SourcePictureBoxGraphics.ReleaseHdc();

                                        CameraRenderer.Render(bc.BackPictureBoxGraphics.GetHdc().ToPointer(), bc.Camera.BackBuffer, Global.AeraWidth, Global.AeraHeight);
                                        bc.BackPictureBoxGraphics.ReleaseHdc();

                                        CameraRenderer.Render(bc.SubPictureBoxGraphics.GetHdc().ToPointer(), bc.Camera.SubBuffer, Global.AeraWidth, Global.AeraHeight);
                                        bc.SubPictureBoxGraphics.ReleaseHdc();

                                        bc.GraphicsCard.CompleteFrameIndex = -1;
                                }

                                Thread.Sleep(5);
                        }
                }

                private void MainTimer_Tick(object sender, EventArgs e)
                {
                        cache.CountTicks++;

                        if (cache.EmptyTicks > 0)
                        {
                                cache.EmptyTicks++;
                        }

                        if (cache.FullTicks > 0)
                        {
                                cache.FullTicks++;
                        }

                        NowLabel.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");

                        TotalCountLabel.Text = cache.TotalCount.ToString();
                        TeamCountLabel.Text = cache.CurrentTeamCount.ToString();

                        StringBuilder sb = new StringBuilder();
                        foreach (var i in cache.Camera.TransportStateHisory)
                        {
                                sb.Append(i);
                                sb.Append(" ");
                        }
                        HistoryLabel.Text = sb.ToString();

                        //StringBuilder sb = new StringBuilder();
                        //foreach (var i in cache.Camera.VAverage)
                        //{
                        //        sb.Append(i);
                        //        sb.Append(" ");
                        //}
                        //VALabel.Text = sb.ToString();

                        LightLabel.Text = cache.Camera.LeftLight.ToString() + " " + cache.Camera.RightLight.ToString();
                }

                private void ExitPictureBox_Click(object sender, EventArgs e)
                {
                        cache.Save();
                        Close();
                }

                private void LoginPictureBox_Click(object sender, EventArgs e)
                {
                        if (cache.Permission.HasFlag(Permissions.修改班组权限))
                        {
                                cache.Permission = Permissions.查询权限;
                        }
                        else
                        {
                                PasswordForm form = new PasswordForm();
                                form.ShowDialog();
                        }

                        UpdateUI();
                }

                private void UpdateUI()
                {
                        if (cache.Permission.HasFlag(Permissions.修改班组权限))
                        {
                                LoginPictureBox.BackgroundImage = UnLockBitmap;
                        }
                        else
                        {
                                LoginPictureBox.BackgroundImage = LockBitmap;
                        }

                        ExitPictureBox.Visible = cache.Permission.HasFlag(Permissions.退出权限);
                }

                private void QueryPictureBox_Click(object sender, EventArgs e)
                {
                        //GraphicsCardForm form = new GraphicsCardForm();
                        QueryForm form = new QueryForm();
                        form.ShowDialog();
                }

                private void AutoCountLabel_Click(object sender, EventArgs e)
                {
                        if (!cache.Permission.HasFlag(Permissions.计数权限))
                        {
                                return;
                        }

                        if (AutoCountLabel.Text == "启动")
                        {
                                AutoCountLabel.Text = "停止";
                                cache.IsAutoCount = false;
                        }
                        else
                        {
                                AutoCountLabel.Text = "启动";
                                cache.IsAutoCount = true;
                                cache.CountTicks = 0;
                                cache.Camera.TransportState = TransportState.无坯;
                                cache.EmptyTicks = 6;
                        }
                }

                private void CameraCountLabel_Click(object sender, EventArgs e)
                {
                        if (!cache.Permission.HasFlag(Permissions.修改铸坯权限))
                        {
                                return;
                        }

                        CameraCountForm form = new CameraCountForm();
                        form.ShowDialog();

                        CameraCountLabel.Text = cache.Camera.Count.ToString();
                }

                private void TeamNameLabel_Click(object sender, EventArgs e)
                {
                        if (!cache.Permission.HasFlag(Permissions.修改班组权限))
                        {
                                return;
                        }

                        TeamForm form = new TeamForm();
                        form.ShowDialog();

                        TeamNameLabel.Text = cache.CurrentTeam.Name;
                        TeamCountLabel.Text = cache.CurrentTeamCount.ToString();
                        TeamStartTimeLabel.Text = cache.CurrentTeamStartTime;
                }

                private void MainPictureBox_MouseDown(object sender, MouseEventArgs e)
                {
                        if (e.Button != MouseButtons.Left)
                        {
                                return;
                        }

                        if (!cache.Permission.HasFlag(Permissions.修改图像权限))
                        {
                                return;
                        }

                        if (e.X > cache.Camera.ForeAeraLeft && e.X < cache.Camera.ForeAeraRight && e.Y > cache.Camera.ForeAeraTop && e.Y < cache.Camera.ForeAeraBottom)
                        {
                                CameraAeraForm form = new CameraAeraForm();
                                form.AreaName = "Fore";
                                form.ShowDialog();
                                return;
                        }

                        if (e.X > cache.Camera.BackAeraLeft && e.X < cache.Camera.BackAeraRight && e.Y > cache.Camera.BackAeraTop && e.Y < cache.Camera.BackAeraBottom)
                        {
                                CameraAeraForm form = new CameraAeraForm();
                                form.AreaName = "Back";
                                form.ShowDialog();
                                return;
                        }

                        GraphicsCardForm gform = new GraphicsCardForm();
                        gform.ShowDialog();
                }
        }
}